/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * LoginFrame.java
 *
 * Created on Jan 17, 2013, 1:34:20 PM
 */
package com.ivanbiz.gui;

import com.birosoft.liquid.LiquidLookAndFeel;
import com.ivanbiz.dao.CompanyDAO;
import com.ivanbiz.dao.LockDateDAO;
import com.ivanbiz.dao.LoginHistoryDAO;
import com.ivanbiz.dao.UserDAO;
import com.ivanbiz.dao.impl.CompanyDAOImpl;
import com.ivanbiz.dao.impl.LockDateDAOImpl;
import com.ivanbiz.dao.impl.LoginHistoryDAOImpl;
import com.ivanbiz.dao.impl.UserDAOImpl;
import com.ivanbiz.helper.GlobalConstant;
import com.ivanbiz.helper.MD5;
import com.ivanbiz.helper.MyUniqueNumber;
import com.ivanbiz.helper.UserSession;
import com.ivanbiz.model.Company;
import com.ivanbiz.model.LoginHistory;
import com.ivanbiz.model.User;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Administrator
 */
public class LoginFrame extends javax.swing.JFrame {

    CompanyDAO companyDAO = new CompanyDAOImpl();
    List<Company> listCompany = new ArrayList<Company>();
    UserDAO userDAO = new UserDAOImpl();
    LoginHistoryDAO loginHistoryDAO = new LoginHistoryDAOImpl();

    /** Creates new form LoginFrame */
    public LoginFrame() {
        try {
            initComponents();
            updateData();
            LockDateDAO dao = new LockDateDAOImpl();
            dao.lockAndCheckToday(new Date());
            MyUniqueNumber myUniqueNumber = new MyUniqueNumber();
            myUniqueNumber.setDateUniqueNumber();

        } catch (Exception ex) {
            Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        textAreaCompanyInfo = new javax.swing.JTextArea();
        labelCompanyLogo = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel4 = new javax.swing.JLabel();
        textUserName = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        textPassword = new javax.swing.JPasswordField();
        buttonCancel = new javax.swing.JButton();
        buttonLogin = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        textAreaCompanyInfo.setColumns(20);
        textAreaCompanyInfo.setEditable(false);
        textAreaCompanyInfo.setFont(new java.awt.Font("Monospaced", 1, 14)); // NOI18N
        textAreaCompanyInfo.setRows(5);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelCompanyLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(textAreaCompanyInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 391, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 513, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textAreaCompanyInfo, 0, 0, Short.MAX_VALUE)
                    .addComponent(labelCompanyLogo, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(14, 14, 14)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jLabel4.setFont(new java.awt.Font("Monospaced", 1, 14));
        jLabel4.setText("User Name");

        textUserName.setFont(new java.awt.Font("Monospaced", 1, 14));

        jLabel5.setFont(new java.awt.Font("Monospaced", 1, 14));
        jLabel5.setText("Password");

        textPassword.setFont(new java.awt.Font("Monospaced", 1, 14)); // NOI18N
        textPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textPasswordKeyPressed(evt);
            }
        });

        buttonCancel.setFont(new java.awt.Font("Monospaced", 1, 14));
        buttonCancel.setText("Cancel");
        buttonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCancelActionPerformed(evt);
            }
        });

        buttonLogin.setFont(new java.awt.Font("Monospaced", 1, 14)); // NOI18N
        buttonLogin.setText("Login");
        buttonLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonLoginActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE)
                    .addComponent(textUserName, javax.swing.GroupLayout.DEFAULT_SIZE, 411, Short.MAX_VALUE))
                .addContainerGap())
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(330, Short.MAX_VALUE)
                .addComponent(buttonLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 109, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textUserName, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textPassword, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonLogin)
                    .addComponent(buttonCancel))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-521)/2, (screenSize.height-257)/2, 521, 257);
    }// </editor-fold>//GEN-END:initComponents

    private void buttonLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonLoginActionPerformed
        try {
            MD5 md5 = new MD5(textPassword.getText());
            User user = userDAO.login(textUserName.getText(), md5.asHex());
            if (user.getIsActive().equals(GlobalConstant.Y)) {
                //if (user.getIsLogin().equals(GlobalConstant.N)) {
                UserSession.setUser(user);
                LoginHistory loginHistory = new LoginHistory();
                loginHistory.setUser(user);
                loginHistory.setDateMasuk(new Date());
                loginHistory.setDateKeluar(GlobalConstant.N);
                user.setIsLogin(GlobalConstant.Y);
                loginHistoryDAO.save(loginHistory, user);
                MainFrame mainFrame = new MainFrame();
                mainFrame.setVisible(true);
                this.setVisible(false);
                //} else {
                //    JOptionPane.showMessageDialog(null, GlobalConstant.USER_LOGIN);
                //    System.exit(0);
                //}
            } else {
                JOptionPane.showMessageDialog(null, GlobalConstant.USER_NOT_ACTIVE);
                System.exit(0);
            }
        } catch (Exception ex) {
            Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_buttonLoginActionPerformed

    private void buttonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCancelActionPerformed
        this.setVisible(false);
        System.exit(0);
    }//GEN-LAST:event_buttonCancelActionPerformed

    private void textPasswordKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textPasswordKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            try {
                MD5 md5 = new MD5(textPassword.getText());
                User user = userDAO.login(textUserName.getText(), md5.asHex());
                if (user.getIsActive().equals(GlobalConstant.Y)) {
                    //if (user.getIsLogin().equals(GlobalConstant.N)) {
                    UserSession.setUser(user);
                    LoginHistory loginHistory = new LoginHistory();
                    loginHistory.setUser(user);
                    loginHistory.setDateMasuk(new Date());
                    loginHistory.setDateKeluar(GlobalConstant.N);
                    user.setIsLogin(GlobalConstant.Y);
                    loginHistoryDAO.save(loginHistory, user);
                    MainFrame mainFrame = new MainFrame();
                    mainFrame.setVisible(true);
                    this.setVisible(false);
                    //} else {
                    //    JOptionPane.showMessageDialog(null, GlobalConstant.USER_LOGIN);
                    //    System.exit(0);
                    //}
                } else {
                    JOptionPane.showMessageDialog(null, GlobalConstant.USER_NOT_ACTIVE);
                    System.exit(0);
                }
            } catch (Exception ex) {
                Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_textPasswordKeyPressed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                try {
                    LiquidLookAndFeel.setLiquidDecorations(true, "mac");
                    UIManager.setLookAndFeel(new LiquidLookAndFeel());
                    new LoginFrame().setVisible(true);
                } catch (UnsupportedLookAndFeelException ex) {
                    Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton buttonCancel;
    private javax.swing.JButton buttonLogin;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel labelCompanyLogo;
    private javax.swing.JTextArea textAreaCompanyInfo;
    private javax.swing.JPasswordField textPassword;
    private javax.swing.JTextField textUserName;
    // End of variables declaration//GEN-END:variables

    private void updateData() {
        try {
            Company company = (Company) companyDAO.getDataByEqual(Company.class, "id", Long.parseLong("1"));
            if (company != null) {
                String telp = null;
                String fax = null;
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(company.getNama()).append("\n");
                //stringBuilder.append(company.getAlamat()).append("\n");
                telp = company.getTelp() == null ? GlobalConstant.TELP + GlobalConstant.MIN : GlobalConstant.TELP + company.getTelp();
                fax = company.getFax() == null ? GlobalConstant.FAX + GlobalConstant.MIN : GlobalConstant.FAX + company.getFax();
                stringBuilder.append(telp).append(GlobalConstant.SPACE).append(fax);
                textAreaCompanyInfo.setText(stringBuilder.toString());
                labelCompanyLogo.setIcon(new ImageIcon(company.getLogo() == null ? GlobalConstant.EMPTY_STRING : company.getLogo()));
                company.setAlias(company.getAlias());
                this.setTitle(company.getNama());
                UserSession.setCompany(company);
            }
        } catch (Exception ex) {
            Logger.getLogger(LoginFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
